#include "app_win.h"
#include "../part/dialog.h"
#include "ui_appwin.h"
#include <QDebug>
#include "../../utils/log.h"
#include <QFileDialog>
#include "../../rt/work.h"


rt::Task2<> test_fut() {
    co_await rt::delay(500);
    log_printf("Delay 500 finish");
    co_await rt::delay(1000);
    log_printf("finish");
}

AppWin::AppWin(QWidget *parent) : QWidget(parent), ui(new Ui::AppWin) {
    ui->setupUi(this);
    setWindowTitle("橙汁机");

    connect(ui->m_btn_play, &QPushButton::clicked, this, &AppWin::clickPlay);
    connect(ui->m_btn_stop, &QPushButton::clicked, this, &AppWin::clickStop);
    connect(ui->m_btn_test_fut, &QPushButton::clicked, [this] () {
        def_task = test_fut();
    });
}

AppWin::~AppWin() { delete ui; }


void AppWin::clickPlay() {
    m_files =  QFileDialog::getOpenFileNames(this);
    m_index = 0;
    if (m_files.isEmpty()) {
        return;
    }
    play_next();
}

void AppWin::play_next() {
    if (m_index >= m_files.size()) {
        m_index = 0;
    }

    m_player = std::make_unique<MutePlayer>( m_files[m_index], ui->m_lb_play  );
    connect(m_player.get(), &MutePlayer::error, this, &AppWin::playErr, Qt::QueuedConnection);
    connect(m_player.get(), &MutePlayer::success, this, &AppWin::playSucc, Qt::QueuedConnection);
    connect(m_player.get(), &MutePlayer::complete, this, &AppWin::playComplete, Qt::QueuedConnection);
    
    m_player->play();
    m_index ++;
}

void AppWin::clickStop() {
    m_player = nullptr;
}

void AppWin::playErr() {
    log_printf("play err");
}

void AppWin::playSucc() {
    play_next();
}

void AppWin::playComplete() {
    
}


